package com.tensquare.mail.listener;

import com.alibaba.fastjson.JSONObject;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
 * 发邮件验证码.
 *
 * @author 宫新程
 * @since 2019/3/9 16:36
 */
@Slf4j
@Component
@RabbitListener(queues = "mail")
public class MailListener {

  @Resource private JavaMailSender mailSender;

  /** 发送短信验证码. */
  @RabbitHandler
  public void sendMail(Map<String, String> map) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("gongxincheng1@163.com");
    message.setTo(map.get("mail"));
    message.setSubject("GXC验证码");
    message.setText("欢迎注册该平台，验证码为：" + map.get("code") + "，感谢！");
    try {
      log.info("开始发送邮件：{}", JSONObject.toJSONString(map));
      mailSender.send(message);
      log.info("邮件发送成功");
    } catch (Exception e) {
      log.error("邮件发送失败：{}", e.getMessage());
    }
  }
}
